package com.chineseall.app.ws;

import java.io.IOException;
import java.net.URI;

import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import javax.websocket.server.PathParam;

import jmind.core.support.LogUtil;

import com.chineseall.app.MTypes;
import com.chineseall.app.pojo.mongo.MMessage;
import com.mongodb.util.JSON;

/***
 * https://blogs.oracle.com/arungupta/entry/websocket_client_and_server_endpoint
 * @author wbxie
 * 2013-12-24
 */
@ClientEndpoint
public class WebSocketClient {

    @OnOpen
    public void open(Session session, EndpointConfig conf, @PathParam("userType") int userType) {
        MMessage message = new MMessage();
        message.mtype(MTypes.CLIENT_OPEN);
        message.put("mid", "wave");
        LogUtil.debug(message.toString());
        SendMessage.send(session, message);

    }

    @OnClose
    public void close(Session session, CloseReason reason) {
        LogUtil.debug(reason.toString());
    }

    @OnMessage
    public void message(Session session, String text) {
        LogUtil.debug(text);
        MMessage m = (MMessage) JSON.parse(text);
        if (m.mtype() == MTypes.SERVER_OPEN) {
            MMessage message = new MMessage();
            message.mtype(MTypes.CLIENT_LOGIN);
            message.put("tokenId", "aGQxZWo2MkA6MTM4Nzc3ODE2MzoxNTc1NjkxNw==");
            SendMessage.send(session, message);
        }
        MMessage message = new MMessage();
        message.mtype(MTypes.CLIENT_HEARTBEAT);
        SendMessage.send(session, message);

    }

    @OnMessage
    public void pongMessage(Session session, PongMessage msg) {

    }

    @OnError
    public void error(Session session, Throwable e) {
        e.printStackTrace();
        //    ConnectionManager.INSTANCE.remove(this);
        //    logger.error("@OnError={},{}", e.getMessage(), this);
    }

    public static void main(String[] args) {
        LogUtil.debug("start ws ");
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://127.0.0.1:9079/chat";
        try {
            URI uri2 = URI.create(uri);
            LogUtil.debug(uri2.toString());
            container.connectToServer(WebSocketClient.class, uri2);

        } catch (DeploymentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
